<template>
  <div class="app-container">
    <el-row :gutter="15" class="mb8">
      <el-form
        :model="formData"
        @submit.prevent
        :inline="true"
        class="el-form-search"
      >
        <!--设备选择-->
        <el-form-item label="设备" porp="device" class="el-form-search-item">
          <el-select
            v-model="formData.device"
            placeholder="请选择设备类型"
            clearable
            filterable
            @change="setChannelList"
          >
            <el-option
              v-for="device in deviceList"
              :key="device.zhGuid"
              :label="device.devName"
              :value="device.zhGuid"
            />
          </el-select>
        </el-form-item>
        <!--通道选择-->
        <el-form-item label="通道" porp="channel" class="el-form-search-item">
          <el-select v-model="formData.channel" placeholder="请选择设备类型" clearable
                     filterable
          >
            <el-option
              v-for="channel in channelList"
              :key="channel.tdGuid"
              :label="channel.channelName"
              :value="channel.tdGuid"
            />
          </el-select>
        </el-form-item>
        <!--数据类型-->
        <el-form-item
          label="数据类型"
          porp="selectedTable"
          class="el-form-search-item"
        >
          <el-select
            v-model="formData.selectedTable"
            placeholder="请选择数据类型"
          >
            <el-option
              v-for="table in tables"
              :key="table.value"
              :label="table.label"
              :value="table.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="时间" porp="timeRange" class="el-form-search-item">
          <!-- 时间选择 -->
          <el-date-picker
            v-model="formData.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 400px"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <!-- 查询按钮 -->
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-search"
          @click="getList"
        >搜索
        </el-button
        >
      </el-form>
    </el-row>

    <!-- 数据表格 -->
    <el-table border :data="tableData" >
      <el-table-column prop="timedate" label="时间" width="150" align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.timedate) }}</span>
        </template>
      </el-table-column>
      <el-table-column v-for="item in fieldsList" :key="item.id" :prop="item.fieldName" :label="item.fieldCnName">
      </el-table-column>
      <el-table-column  fixed="right" label="操作" width="100">
        <template slot-scope="scope">
          <el-button @click="handleClick(scope.row)" type="text" size="small"
          >查看
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="formData.pageNum"
      :limit.sync="formData.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { getDBIhrc } from '@/api/data_analysis/baseData.js'
import { getDeviceListFold } from '@/api/device/device'
import { getToken } from "@/utils/auth";
import {getSettingQueryFields} from '@/api/system/settingQUeryFields'
import {getTableDefinition} from '@/api/system/settingQUeryFields'

export default {
  data() {
    return {
      total: 0,
      tableHeight: window.innerHeight-180,
      tables: [
        { value: 'base', label: '原始数据' },
        { value: 'avg', label: '平均值' },
        { value: 'max', label: '最大值' },
        { value: 'min', label: '最小值' }
      ],
      formData: {
        pageNum: 1,
        pageSize: 30,
        selectedTable:'base',
        timeRange: [
          new Date(2025, 0, 20), // 月份从0开始（0=1月）
          new Date(2025, 0, 22)
        ],
        device: '',
        channel: '',
        tableInfo:"db_ihrc",

      },

      tableData: [],
      deviceList: [],
      channelList: [],
      fieldsList:[],
      tableInfoList:[],
    }
  },
  created() {
    this.getFieldsAndTableList()
    this.getDeviceList()
    this.loadData()
  },
  methods: {
    getFieldsAndTableList(e){
      getSettingQueryFields({
        tablePrefix: e || "db_ihrc",
        isShow:1,
      }).then(response => {
        this.fieldsList = response.rows;
        console.log(this.fieldsList);
      })

      getTableDefinition().then(response => {
        this.tableInfoList = response.rows;
        console.log(this.tableInfoList);
      })
    },
    getList() {

      // 格式化日期为后端期望的格式
      const formatDate = (date) => {
        const d = new Date(date)
        const pad = (num) => (num < 10 ? '0' + num : num)

        return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
      }
      console.log(this.fieldsList.map((item) => item.fieldName))
      getDBIhrc({
        pageNum: this.formData.pageNum,
        pageSize: this.formData.pageSize,
        tdGuid: this.formData.channel,
        tableName: this.formData.tableInfo + (this.formData.selectedTable === 'base'?"":this.formData.selectedTable),
        fields:this.fieldsList.map((item) => item.fieldName),
        startTime: formatDate(this.formData.timeRange[0]),
        endTime: formatDate(this.formData.timeRange[1])
      })
        .then((res) => {

          console.log(res)
          this.tableData = res.rows
          this.total = res.total
        })
        .catch((err) => {
          this.$message.error('数据加载失败')
        })
    },
    loadData() {
      if (
        !this.formData.selectedTable ||
        !this.formData.timeRange?.length === 2
      ) {
        this.$message.warning('请选择表和时间范围')
        return
      }

      this.getList()
    },

    handleClick(row) {
      let suffix
      if (this.formData.selectedTable !== 'db_basedata') {
        suffix = this.formData.selectedTable.slice(-3)
      }
      //跳转到详细页面
      this.$router.push({
        path: '/data/data-detail',
        name: 'dataDetail',
        params: {
          timedate: row.timedate,
          tableNameSuffix: this.formData.selectedTable === 'base'?"":this.formData.selectedTable,
          tdGuid: row.tdGuid
        }
      })
    },

    getDeviceList() {
      getDeviceListFold().then((res) => {
        console.log(res)
        this.deviceList = res.rows
      })
    },
    setChannelList(selectedValue) {
      console.log(selectedValue)
      console.log(this.deviceList)

      this.channelList = this.deviceList.filter((item) => {
        return item.zhGuid === selectedValue
      })[0].channelList
    },
    // handelTableInfoChang(e){
    //
    //   this.getFieldsAndTableList(e)
    // }
  }
}
</script>
